package 数组.移除元素_快慢指针.删除重复项;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/11 14:53
 * @description:给你一个 升序排列 的数组 nums ，请你 原地 删除重复出现的元素，使每个元素 只出现一次 ，
 * 返回删除后数组的新长度。元素的 相对顺序 应该保持 一致
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr = {1,1,2};
        System.out.println(remove(arr));
    }


    //快慢指针
    public static int removeDuplicates(int[] nums) {
        int slowIndex = 0;
        for (int fastIndex = 1; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != nums[fastIndex-1]){
                slowIndex++;
                nums[slowIndex] = nums[fastIndex];
            }
        }
        return slowIndex+1;
    }

    public static int remove(int[] nums) {
        if (nums.length == 1) {
            return 1;
        }
        int slow = 0;
        int fast = 1;
        while (fast <= nums.length - 1) {
            if (nums[fast] != nums[slow]) {
                slow++;
                nums[slow] = nums[fast];
            }
            fast++;
        }
        return slow + 1;
    }
}
